//
//  LBMTextView.swift
//  EmoticonKeyboard
//
//  Created by 刘保满 on 16/6/2.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit

class LBMTextView: UITextView {
    
    func insertEmoticon(em: LBMEmoticon) {
        
        //如果点击的是空白的模型,直接返回
        if em.isEmpty {
            return
        }
        //点击删除按钮
        if em.isDelete {
            //执行回删
            deleteBackward()
            return
        }
        
        //如果点击的是emojicon
        if em.emojiStr != nil {
            
            //把表情添加到对应的光标下
            replaceRange(selectedTextRange!, withText: em.emojiStr ?? "")
            return
        }
        
        //获取附件对象
        let imageText = LBMTextAttachment.emoticonImageToImageText(em, font: font!)
        
        //5.将textView.attributedText转换为可变的属性文本
        let strM = NSMutableAttributedString(attributedString: attributedText)
        //6.在替换之前记录光标所在位置
        let range = selectedRange
        
        //7.替换属性文本
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        
        //8.重新设置
        attributedText = strM
        
        //9.恢复光标的位置
        selectedRange = NSMakeRange(range.location + 1, 0)
        
        //在这里主动调用协议方法,让文本框发生改变,"发送" 呈可发送状态
        self.delegate?.textViewDidChange?(self)
        
    }
    
    //获取普通文本 + 图片对应的chs
    func fullText() -> String {
        
        let attr = attributedText
        var strM = String()
        attr.enumerateAttributesInRange(NSMakeRange(0, attr.length), options: []) { (dict, range, _) in
            
            if let attachment = dict["NSAttachment"] as? LBMTextAttachment {
                
                strM += (attachment.chs ?? "")
                
            } else {
                let subStr = (self.text as NSString).substringWithRange(range)
                strM += subStr
                
            }
            
        }
        
        return strM
        
    }

}
